﻿namespace MXERP.Infrastructure.Store
{
    public partial class TabState
    {
        public static class Init
        {
            public record Action : IAction { }

            public class Handler : ActionHandler<Action>
            {
                public Handler(IStore store) : base(store) { }
                TabState TabState => Store.GetState<TabState>();
                RouteState RouteState => Store.GetState<RouteState>();

                public override Task Handle(Action action, CancellationToken cancellationToken)
                {
                    var affixRoutes = RouteState.Routes?.Where(x => x.IsAffix).ToList();
                    if (affixRoutes != null && affixRoutes.Count > 0)
                    {
                        var tabs = new List<Tab>();
                        foreach (var affixRoute in affixRoutes)
                        {
                            var tab = new Tab
                            {
                                CreatedOn = DateTime.MinValue,
                                Url = affixRoute.Path ?? "",
                                Title = affixRoute.Title,
                                Icon = affixRoute.Icon,
                                IsAffix = affixRoute.IsAffix,
                                IsKeepAlive = affixRoute.IsKeepAlive
                            };
                            tabs.Add(tab);
                        }
                        TabState.Tabs = tabs;
                    }
                    return Task.CompletedTask;
                }
            }
        }
    }
}
